package com.cfets.annualAssessment.util;

import com.cfets.annualAssessment.entity.SendMail;
import sun.misc.BASE64Encoder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by ShenYiChou on 2017/5/18.
 */
public class MailUtil {
    private static PrintWriter output;
    private static BufferedReader input;
    private static Socket socket = null;
//    static String user = "1163490863@qq.com";

    public static void SendMail(SendMail sendMail) {
        try {
            socket = new Socket("mail.chinamoney.com.cn", 25);
            output = new PrintWriter(new OutputStreamWriter(socket
                    .getOutputStream()));
            input = new BufferedReader(new InputStreamReader(socket
                    .getInputStream()));
//            output.println("hello chinamoney");
            output.flush();
            System.out.println(input.readLine());
            //验证登陆
            output.println("auth login");
            output.flush();
            System.out.println(input.readLine());
            //用户名
//            String username = "shenyichou_zh";
            String username = sendMail.getSender();
            output.println(new BASE64Encoder().encode(username.getBytes()));
            output.flush();
            System.out.println(input.readLine());
            //密码
            String password = "sssyyyccc24";
            output.println(new BASE64Encoder().encode(password.getBytes()));
            output.flush();
            System.out.println(input.readLine());
            //发件人
            output.println("mail from: <"+sendMail.getSender()+"@chinamoney.com.cn>");
            output.flush();
            System.out.println(input.readLine());
            //收件人
            output.println("rcpt to: <" + sendMail.getReceiver() + ">");
            output.flush();
            System.out.println(input.readLine());

            //内容
            output.println("data");
            output.flush();
            System.out.println(input.readLine());
            String con = "From: "+sendMail.getSender()+"@chinamoney.com.cn\r\n";
            con += "To: <" + sendMail.getReceiver() + ">\r\n";
            con = con + "Subject: "+ sendMail.getSubject()+"\r\n";
            con = con + "Content-Type: text/plain;charset=\"gb2312\"\r\n";
            con = con + "\r\n";
            con = con + sendMail.getMailMsg()+"\r\n";
            con = con + ".\r\n";
            output.println(con);
            output.flush();
            System.out.println(input.readLine());
            System.out.println(input.readLine());
            socket.close();
            input.close();
            output.close();
            System.out.println("Done");

        } catch (Exception e) {
            System.out.println("Error " + e);
            return;
        }
    }
}
